package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.PlanOther;
import net.hn.hnms.biz.plan.mapper.PlanOtherMapper;
import net.hn.hnms.biz.plan.request.PlanOtherReq;
import net.hn.hnms.biz.plan.service.IPlanOtherService;
import net.hn.hnms.biz.plan.vo.PlanOtherVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author zhaoyang
 * 其他生产计划管理服务层实现
 * @date 2022-08-02
 */
@Service
@DS("master")
public class PlanOtherServiceImpl extends BaseService<PlanOther, PlanOtherVO> implements IPlanOtherService {

    private PlanOtherMapper planOtherMapper;
    @Autowired
    private RemoteUserService remoteUserService;
    public PlanOtherServiceImpl(PlanOtherMapper planOtherMapper) {
        this.planOtherMapper = planOtherMapper;
    }

    /**
     *
     * @param planOther
     * @param pageQuery
     *
     * 查询其他生产计划列表
     */
    @Override
    public ResponsePage<PlanOtherVO> selectPageList(PlanOtherReq planOther, PageQuery pageQuery) {
        Page<PlanOther> page = planOtherMapper.selectPage(pageQuery.build(), buildQuery(planOther).orderByDesc(PlanOther::getOtherPlanCode).orderByDesc(PlanOther::getCreateTime));
        List<PlanOtherVO> list = page.getRecords().stream().map(o -> convert(o, PlanOtherVO.class,o.getOtherPlanType())).collect(Collectors.toList());
        list.forEach(ii->{
            LoginUser userInfoById = remoteUserService.getUserInfoById(Long.valueOf(ii.getCreateUserId()));
            if (Optional.ofNullable(userInfoById).isPresent()) {
                ii.setCreateUserName(userInfoById.getNickname());
            }

        });

        return new ResponsePage<>(list, page.getTotal());
    }

    /**
     * 构造查询条件
     * @param req
     * @return LambdaQueryWrapper<PlanDevelopment> 查询条件
     */
    private LambdaQueryWrapper<PlanOther> buildQuery(PlanOtherReq req){
        LambdaQueryWrapper<PlanOther> lqw = new LambdaQueryWrapper<PlanOther>()
                .like(StrUtil.isNotBlank(req.getOtherPlanCode()), PlanOther::getOtherPlanCode, req.getOtherPlanCode())
                .like(StrUtil.isNotBlank(req.getOtherPlanName()), PlanOther::getOtherPlanName, req.getOtherPlanName())
//                .eq(StrUtil.isNotBlank(req.getMineCode()), PlanOther::getMineCode, req.getMineCode())
                .eq(StrUtil.isNotBlank(req.getOtherPlanType()), PlanOther::getOtherPlanType, req.getOtherPlanType())
                .eq(StrUtil.isNotBlank(req.getStatus()), PlanOther::getStatus, req.getStatus())
                .and(o->o.eq(req.getMineCode()!=null, PlanOther::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, PlanOther::getCompanyCode, req.getCompanyCode()));

        return lqw;
    }

    /**
     *
     * @param PlanOther
     * 查询掘进计划列表
     */
    @Override
    public List<PlanOtherVO> selectList(PlanOtherReq PlanOther) {
        List<PlanOther> list = planOtherMapper.selectList(buildQuery(PlanOther));
        return list.stream().map(o ->  convert(o, PlanOtherVO.class,o.getOtherPlanType())).collect(Collectors.toList());
    }

    /**
     *
     * @param planOther
     * 新增其他生产计划
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(PlanOtherReq planOther) {

        PlanOther insertObj = new PlanOther();
        copyProperties(planOther, insertObj, planOther.getOtherPlanType());
        //自动生成 计划名称 计划编号
        insertObj.setOtherPlanName(generatePlanName(planOther.getOtherPlanType(),insertObj.getPlanStartDate()));
        insertObj.setOtherPlanCode(generatePlanCode(planOther.getOtherPlanType(),insertObj.getPlanStartDate()));
        insertObj.setStatus("0");
        QueryWrapper<PlanOther> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("other_plan_code", insertObj.getOtherPlanCode());
        if (planOtherMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        return planOtherMapper.insert(insertObj);
    }

    /**
     *
     * @param idList
     * 批量删除
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
  planOtherMapper.deleteBatchIds(idList);
    }

    /**
     *
     * @param planOther
     * 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(PlanOtherReq planOther) {
        if (StrUtil.isBlank(planOther.getOtherPlanId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }
        PlanOther updateObj = new PlanOther();
        copyProperties(planOther, updateObj, planOther.getOtherPlanType());
        updateObj.setOtherPlanName(generatePlanName(planOther.getOtherPlanType(),updateObj.getPlanStartDate()));
        updateObj.setOtherPlanCode(generatePlanCode(planOther.getOtherPlanType(),updateObj.getPlanStartDate()));
        QueryWrapper<PlanOther> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("other_plan_code", updateObj.getOtherPlanCode());
        queryWrapper.ne("other_plan_id", updateObj.getOtherPlanId());
        if (planOtherMapper.selectCount(queryWrapper) > 0) {
            throw new HuaNengException(Constants.FAIL, "已存在同一时段的计划");
        }
        int updateCount = planOtherMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }

    }

    /**
     *
     * @param id
     * 按主键id查询详情
     */
    @Override
    public PlanOtherVO selectDetailById(String id) {
        PlanOther planOther = planOtherMapper.selectById(id);
        if (planOther == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(planOther, PlanOtherVO.class);
    }

    /**
     * 启用/禁用
     * @param id 数据id
     * @param status  status: 0:启用 1:禁用
     */
    public void changeStatus(String id, Integer status) {
        if (status == 1 || status == 0) {
            PlanOther planMining = planOtherMapper.selectById(id);
            if (planMining == null) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            planMining.setStatus(status + "");
            int res = planOtherMapper.updateById(planMining);
            if (res == 0) {
                throw new HuaNengException(Constants.FAIL, "数据不存在");
            }
            return;
        }
        throw new HuaNengException(Constants.FAIL, "传入的参数错误");
    }
}
